package sign_in.loginsystem.tool;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;
import sign_in.loginsystem.mapper.RoleAndPemMapper;
import sign_in.loginsystem.mapper.UserMapper;
import sign_in.loginsystem.model.entity.Menu;
import sign_in.loginsystem.model.entity.Role;
import sign_in.loginsystem.model.entity.User;

import java.util.ArrayList;
import java.util.Map;

@Service
public class AnalyzeToken implements Analyze {

    @Resource
    UserMapper userMapper;

    @Resource
    RoleAndPemMapper roleAndPemMapper;

    @Override
    public User analyzeToken(String token){

        JWTVerifier verifier = JWT.require(Algorithm.HMAC256("iosLaboratory")).build();
        DecodedJWT decodedJWT = null;
        try {
            decodedJWT = verifier.verify(token);
        } catch (Exception e) {
            System.out.println("无法解析令牌");
            return null;
        }
        Map<String, Claim> claims = decodedJWT.getClaims();
        return roleOfUser(userMapper.search(claims.get("username").asString(), claims.get("password").asString()));
    }

    @Override
    public boolean permissionOrNot(String pemKey, String token) {
        User user = analyzeToken(token);
        if (user==null){
            return false;
        }
        Role role = user.getRole();
        ArrayList<Menu> menus = role.getMenus();
        for(Menu menu : menus){
            if (menu.getPemKey().equals(pemKey)) {
                return true;
            }
        }
        return false;
    }

    private User roleOfUser(User user){
        Role role = roleAndPemMapper.searchUserRole(user);
        ArrayList<Integer> pemId = roleAndPemMapper.searchRolePemId(role);
        role.setMenus(roleAndPemMapper.searchRolePem(pemId));
        user.setRole(role);
        return user;
    }

}
